package org.nowcoder.leetcode.twoPointers;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Title  : 18. 4Sum
 * Source : https://leetcode.cn/problems/4sum/
 * Author : XrazYang
 * Date   : 2023-07-19
 */


public class LeetCode_18 {

    public List<List<Integer>> fourSum(int[] nums, int target) {
        //方法一： 暴力解法： 四重循环，肯定超时

        //方法二： 排序 + 双重指针
        List<List<Integer>> results = new ArrayList<>();
        if (nums.length < 4) {
            return results;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 3; i++) {
            if (i - 1 >= 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < nums.length - 2; j++) {
                if (j - 1 > i && nums[j] == nums[j - 1]) {
                    continue;
                }
                int left = j + 1;
                int right = nums.length - 1;
                while (left < right) {
                    BigInteger big =
                            BigInteger.valueOf(nums[i]).add(BigInteger.valueOf(nums[j])).add(BigInteger.valueOf(nums[left])).add(BigInteger.valueOf(nums[right]));
                    if (big.longValue() == target) {
                        List<Integer> temp = new ArrayList<>();
                        temp.add(nums[i]);
                        temp.add(nums[j]);
                        temp.add(nums[left]);
                        temp.add(nums[right]);
                        results.add(temp);
                        while (left < right && nums[left] == nums[left + 1])
                            left++;
                        while (left < right && nums[right] == nums[right - 1])
                            right--;
                        left++;
                        right--;
                    } else if (big.longValue() < target) {
                        left++;
                    } else {
                        right--;
                    }
                }
            }
        }
        return results;
    }
}
